/*
 * @Author: szx
 * @Date: 2021-12-03 13:29:48
 * @LastEditTime: 2021-12-03 13:58:21
 * @Description:
 * @FilePath: \leetcode\1-99\54\54.js
 */
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
// var spiralOrder = function (matrix) {
//     const m = matrix.length,
//         n = matrix[0].length;
//     const res = [];
//     let up = 0,
//         down = m - 1,
//         left = 0,
//         right = n - 1;
//     while (true) {
//         for (let j = left; j <= right; j++) res.push(matrix[up][j]);
//         if (++up > down) break;
//         for (let i = up; i <= down; i++) res.push(matrix[i][right]);
//         if (--right < left) break;
//         for (let j = right; j >= left; j--) res.push(matrix[down][j]);
//         if (--down < up) break;
//         for (let i = down; i >= up; i--) res.push(matrix[i][left]);
//         if (++left > right) break;
//     }
//     return res;
// };

var spiralOrder = function (matrix) {
    const result = [];
    let left = 0;
    let right = matrix[0].length - 1;
    let top = 0;
    let bottom = matrix.length - 1;
    let numEle = matrix.length * matrix[0].length;
    while (numEle >= 1) {
        for (let i = left; i <= right && numEle >= 1; i++) {
            result.push(matrix[top][i]);
            numEle--;
        }
        top++;
        for (let i = top; i <= bottom && numEle >= 1; i++) {
            result.push(matrix[i][right]);
            numEle--;
        }
        right--;
        for (let i = right; i >= left && numEle >= 1; i--) {
            result.push(matrix[bottom][i]);
            numEle--;
        }
        bottom--;
        for (let i = bottom; i >= top && numEle >= 1; i--) {
            result.push(matrix[i][left]);
            numEle--;
        }
        left++;
    }
    return result;
};
